'''
Created on 28.12.2012

@author: doleynik
'''
import time
import json
import webapp2
from webapp2_extras.i18n import gettext as _

from google.appengine.api import users
from apnetmodels.basicmodels import immeuble, invoice, payment
from common import functions
from wtforms.ext.appengine.db import model_form
from BaseHandler import BaseHandler

class Payments(BaseHandler):
    def __init__(self, *args, **kwargs):
        super(Payments, self).__init__(*args, **kwargs)
        self.au = functions.GetAPNETUser()
        if not self.au:
            self.redirect(users.create_login_url(self.request.uri))
            return
        self.fields = {'invoice': _('Invoice'), 'immeuble': _('Tenement'), 'date': _('Payment date'),
                       'amount': _('Amount to pay'), 'responsible': _('Responsible'), 'method_of_payment': _('Payment method'),
                       'check_number': _('Check number'), 'approved_flag': _('Approved'), 'approved_by': _('Approved by'),
                       'supplier': _('Supplier'), 'invoice_date': _('Invoice date'), 'paid_amount': _('Paid amount'),
                       'amount_ttc': _('Amount TTC'), 'locked_amount': _('Pending amount')
                       }
    
    def get(self, *args, **kwargs):
        self.get_method(self.__class__, *args, **kwargs)

    def post(self, *args, **kwargs):
        self.get_method(self.__class__, *args, **kwargs)
        
    def op_list(self, *args, **kwargs):
        imm_id = kwargs.get('imm_id', -1)
        imm = immeuble.get_by_id(int(imm_id))
        if not imm:
            self.redirect(webapp2.uri_for('mainpage'))
            return
        
        template_values = {
                           'title': _('Payments to suppliers. %s' % imm.name),
                           'header': _('%s. Payments to suppliers.' % imm.name),
                           'app_user': self.au,
                           'immeuble': imm,
                           'lurl': users.create_logout_url('/'),
                           'section': 'vie',
                           'leftmenu': 'payments',
                           'fields': self.fields
                           }

        template = self.jinja2.get_template('templates/payments_list.html')
        self.response.out.write(template.render(template_values))
    
    def op_add(self, *args, **kwargs):
        imm_id = kwargs.get('imm_id', -1)
        inv_id = kwargs.get('inv_id', -1)
        imm = immeuble.get_by_id(int(imm_id)) 
        inv = invoice.get_by_id(int(inv_id))
        
        ok_message = ""
        PaymentForm = model_form(payment, only=['date', 'amount', 'method_of_payment', 'check_number'])
        
        inf_msg =  _("Invoice: " + str(inv.number) + " Amount: " + str(inv.amount))
        
        if self.request.method == 'GET':
            form = PaymentForm()
            form['amount'].data = inv.amount - inv.paid_amount 
        if self.request.method == 'POST':
            form = PaymentForm(self.request.POST)
            
            if form.validate():
                new_payment = payment(lastchange_by = self.au, 
                                      invoice = inv, 
                                      immeuble = imm, 
                                      date = form['date'].data,
                                      method_of_payment = form['method_of_payment'].data,
                                      check_number = form['check_number'].data,
                                      amount = form['amount'].data,
                                      responsible = self.au
                                         )
                new_payment.put()
                while not new_payment.is_saved():
                    time.sleep(2)
                inv.locked = True
                inv.pending_amount = inv.pending_amount + new_payment.amount
                inv.put()
                ok_message = _('Payment was added.')
        
        template_values = {'form': form, 'ok_message': ok_message, 'person': inf_msg, 'fields': self.fields}
        
        template = self.jinja2.get_template('templates/base_form.html')
        self.response.out.write(template.render(template_values))
    
    def op_list_json(self, *args, **kwargs):
        imm_id = kwargs.get('imm_id', -1)
        imm = immeuble.get_by_id(int(imm_id))
        if not imm:
            self.redirect(webapp2.uri_for('mainpage'))
            return
        
        payments = imm.payment_set.filter('approved_flag =', False).order('-date').run()
        
        p_list = []
        for p in payments:
            invoice_info = _("Invoice: #" + unicode(p.invoice.number) + " Label: " + unicode(p.invoice.title))
            p_list.append([unicode(p.date), unicode(p.invoice.supplier), unicode(invoice_info), p.invoice.amount, p.amount, unicode(p.responsible), str(p.key().id())])
        ret = {}
        ret['aaData'] = p_list
        self.response.out.write(json.dumps(ret))
        
    
    def op_approve(self, *args, **kwargs):
        imm_id = kwargs.get('imm_id', -1)
        p_id = kwargs.get('inv_id', -1)
        #imm = immeuble.get_by_id(int(imm_id)) 
        pmnt = payment.get_by_id(int(p_id))
        locked = pmnt.amount
        
        PaymentForm = model_form(payment, only=['amount'])
        ok_message = ""
        
        inf_msg =  _("Invoice: " + unicode(pmnt.invoice.number) + " Amount: " + unicode(pmnt.invoice.amount))
        
        if self.request.method == 'GET':
            form = PaymentForm(obj = pmnt)
        if self.request.method == 'POST':
            form = PaymentForm(self.request.POST)
            
            if form.validate():
                pmnt.amount = form['amount'].data
                pmnt.approved_by = self.au
                pmnt.approved_flag = True
                pmnt.put()
                pmnt.invoice.paid_amount = pmnt.invoice.paid_amount + pmnt.amount
                pmnt.invoice.pending_amount = pmnt.invoice.pending_amount - locked
                if pmnt.invoice.paid_amount >= pmnt.invoice.amount:
                    pmnt.invoice.paid = True 
                pmnt.invoice.put()
                ok_message = _('Payment was approved and accounted.')
        
        template_values = {'form': form, 'ok_message': ok_message, 'person': inf_msg, 'fields': self.fields}
        
        template = self.jinja2.get_template('templates/base_form.html')
        self.response.out.write(template.render(template_values))

    